package com.sky.filter;


import com.sky.constant.JwtClaimsConstant;
import com.sky.properties.JwtProperties;
import com.sky.utils.CurrentHolder;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/user/*")//拦截所有请求
/*
 * jwt令牌过滤器
 * */
public class JwtTokenUserFilter implements Filter {


    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {

        log.info("开始进行jwt令牌校验");
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //1.获取当前请求的URL
        String url = request.getRequestURL().toString();
        log.info("当前请求URL: {}", url);


        //2.判断当前Url是否为登录接口或Swagger资源，如果是则直接放行
        if (url.contains("/user/user/login") ||
                url.contains("/user/shop/status")) {
            log.info("当前请求是登录操作或Swagger资源,直接放行");
            filterChain.doFilter(request, response);
            return;
        }

        //3.获取当前请求头中的令牌
        String jwt = request.getHeader(jwtProperties.getUserTokenName());

        //4.校验令牌,判断是否为空,为空的话直接错误结果,未登录
        if (!StringUtils.hasLength(jwt)) {
            log.info("jwt令牌为空,返回未登录的信息");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }

        //5.jwt令牌不为空,则进行解析
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), jwt);

            Long userid = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            CurrentHolder.setCurrentId(userid);

        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败, 返回错误结果");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }

        //6.解析成功,则放行
        log.info("令牌校验成功, 放行");
        filterChain.doFilter(request, response);

        //7.执行完后，移除当前线程的id
        CurrentHolder.remove();
    }
}
